/*
 * Copyright (c) 2007 jNetX.
 * http://www.jnetx.com
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * jNetX. You shall not disclose such Confidential Information and
 * shall use it only in accordance with the terms of the license
 * agreement you entered into with jNetX.
 *
 * $Id$
 */
package com.jnetx.javax.sip.address;

import com.jnetx.javax.sip.util.ByteArrayUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.text.ParseException;

/**
 * @author <a href="mailto:dparhonin@jnetx.ru">Dmitry Parhonin</a>
 * @version $Revision$
 */
class AddressParser {
    private static final Log logger = LogFactory.getLog(SipURIParser.class);

    private AddressParser() {
    }

    //"Mr. Watson" <sip:watson@worcester.jcp.org;tt=1>
    //Bob <mailto:watson@jcp.org.com>; q=0.1
    public static AddressImpl parse(AddressImpl address, byte[] data, int start, int end) throws ParseException {
        if (address == null) address = new AddressImpl(data, start, end);
        start = ByteArrayUtil.firstMissing(data, ' ', start, end);
        if (start == -1)
            fail("Cannot parse the header!", start);
        final int leftQuote = ByteArrayUtil.firstOccurence(data, '<', start, end);
        if (leftQuote != -1) {
            final int rightQuote = ByteArrayUtil.lastOccurence(data, '>', leftQuote, end);
            int startOfName = start;
            int endOfName = ByteArrayUtil.lastMissing(data, ' ', startOfName, leftQuote);
            if (data[startOfName] == '\"' && data[endOfName] == '\"')
                startOfName++;
            else
                endOfName++;
            address.setURI(AddressFactoryImpl.createURILazily(data, leftQuote + 1, rightQuote));
            if (endOfName > startOfName)
                address.setDisplayName(new String(data, startOfName, endOfName - startOfName));
        } else {
            //No angle quotes
            int endOfName = ByteArrayUtil.lastMissing(data, ' ', start, end);
            endOfName = ByteArrayUtil.lastOccurence(data, ' ', start, endOfName);
            if (endOfName != -1) {
                int startOfName = start;
                if (data[startOfName] == '\"' && data[endOfName - 1] == '\"'){
                    startOfName++; endOfName--;
                }
                address.setURI(AddressFactoryImpl.createURILazily(data, endOfName + 1, end));
                address.setDisplayName(new String(data, startOfName, endOfName - startOfName));
            } else {
                address.setURI(AddressFactoryImpl.createURILazily(data, start, end));
            }
        }
        return address;
    }

    private static void fail(String message, int offset) throws ParseException {
        logger.error(message);
        throw new ParseException(message, offset);
    }
}
/*
 * $Log$
 */